package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDTO;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService{

    @Autowired
    DishFlavorService dishFlavorService;

    @Override
    @Transactional  //需要进行两次数据库的保存操作且同时操作两张表   所以加入事物来保证两张表的数据一致性
    public void savewithFlavor(DishDTO dishDTO) {

        //保存菜品的基本信息到菜品表dish中
        this.save(dishDTO);

        //菜品id
        Long dishId = dishDTO.getId();

        //菜品口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors.stream().map((item)->{
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());

        //保存菜品口味到菜品口味表
        dishFlavorService.saveBatch(flavors);
    }


    //根据ID查询菜品信息
    @Override
    public DishDTO getByIdwithFlavor(long id) {
            //查询菜品基本信息， 在dish表中查询
        Dish dish = this.getById(id);

        DishDTO dishDTO = new DishDTO();
        BeanUtils.copyProperties(dish,dishDTO);

        //查询当前的菜品对应的口味，在dish_Flavor表中查询
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
        dishDTO.setFlavors(flavors);
        return dishDTO;
    }

    //更新菜品信息  同时更新对应口味信息
    @Override
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {

        //更新dish表基本信息
        this.updateById(dishDTO);

        //修改当前菜品对应的口味数据--dish_Flavor表的删除操作
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishDTO.getId());

        dishFlavorService.remove(dishFlavorLambdaQueryWrapper);

        //添加当前提交过来的口味数据--dish_Flavor表的添加操作
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors.stream().map((item)->{
            item.setDishId(dishDTO.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);

    }
}
